//===============================
//  功能 ：备注 
//  作者 ：上中野辅亚瑟王 
//  创建时间 ：2023-09-11  18-01-51 
//  Unity版本  ：2019.4.35f1 
//  变更时间 :  2023-09-11  18-01-51 
//===============================





using System;
using System.Security.Cryptography;
using System.Text;

namespace ZS.U3D.BASE.Runtime.AES
{
    public static class AESManager
    {
        private static readonly string BASECHAR = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789*#@";

        /// <summary>
        /// 随机生成AES Key 
        /// </summary>
        /// <returns></returns>
        public static string CreateKey( )
        {
            string key = string.Empty;
            for (int i = 0; i < 32; i++)
            {
                int number = UnityEngine.Random.Range(0, BASECHAR.Length);
                key += BASECHAR[number];
            }
            return key;
        }

        /// <summary>
        ///  AES 加密
        /// </summary>
        /// <param name="str"> 需要加密的字符串 </param>
        /// <param name="key"> 加密的key </param>
        /// <returns></returns>
        public static string Encrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;

            byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);
            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            ICryptoTransform cTransform = rm.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        /// <summary>
        ///  AES 解密
        /// </summary>
        /// <param name="str"> 要解密的字符串 </param>
        /// <param name="key"> 解密的key </param>
        /// <returns></returns>
        public static string Decrypt(string str, string key)
        {
            if (string.IsNullOrEmpty(str)) return null;
            byte[] toEncryptArray = Convert.FromBase64String(str);
            RijndaelManaged rm = new RijndaelManaged
            {
                Key = Encoding.UTF8.GetBytes(key),
                Mode = CipherMode.ECB,
                Padding = PaddingMode.PKCS7
            };
            ICryptoTransform cTransform = rm.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Encoding.UTF8.GetString(resultArray);
        }
    }
}